import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains


class Base():
    # 初始化驱动
    def __init__(self, driver):
        self.driver = driver

    def open_url(self, url):
        self.driver.get(url)

    def time(self, name):
        t = time.strftime("%Y%m%d%H%M%S", time.localtime())
        self.driver.save_screenshot(t + name)

    # 定位
    def find_element(self, loc):
        try:
            WebDriverWait(self.driver, 20, 0.5).until(lambda driver: driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            print(e)
            self.time("den.png")

    # 点击
    def click(self, loc):
        self.find_element(loc).click()

    # 输入
    def send_keys(self, loc, test):
        self.find_element(loc).send_keys(test)

    def two_cl(self, loc):
        gl = self.find_element(loc)
        ActionChains(self.driver).double_click(gl).perform()

    def Keys_Enter(self, loc):
        gl = self.find_element(loc)
        gl.send_keys(Keys.ENTER)

    def Ctrl_A(self, loc):
        gl = self.find_element(loc)
        gl.send_keys(Keys.CONTROL + "a")

    # 切换窗口
    def new_windowhand(self):
        self.driver.driver.switch_to.window(self.driver.window_handles[-1])

    # frame框架方法
    def gen_frame(self, loc):
        iframe = self.find_element(loc)
        self.driver.switch_to.frame(iframe)

    # 滑动
    def hua_scrollTo(self, x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')
